package cn.gok.homework;

import java.io.*;

class School implements Serializable {
    private String name;
    private String address;
    private int birthYear;

    public School(String name, String address, int birthYear) {
        this.name = name;
        this.address = address;
        this.birthYear = birthYear;
    }

    @Override
    public String toString() {
        return "School{" +
                "name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", birthYear=" + birthYear +
                '}';
    }
    public void writeToFile(){
        System.out.println("学校名字:"+this.name+"位于:"+this.address+"成立年份:"+this.birthYear);
    }
}
public class HomeWork {
    public static void main(String[] args) throws IOException {
        //test1();
        test1Read();
    }

    private static void test1Read() throws IOException {
        //读取并且显示
        ObjectInputStream stream = new ObjectInputStream(new FileInputStream("day5\\src\\cn\\gok\\homework\\1.dat"));
        try {
            while (true){
                Object object = stream.readObject();
                if (object instanceof School){
                    ((School) object).writeToFile();
                }
                System.out.println(object);
            }
        } catch (EOFException |ClassNotFoundException e) {
            System.out.println("文件读取结束");
        }
        stream.close();
    }

    private static void test1() throws IOException {
//        1 创建类 School类：name,address,  birthYear成立的年份：int （2002；2010）
//        实现序列化接口，void writeToFile();//采用对象流写入将两个school对象写入到 1.dat中，
//        void readFromFile();//从1.dat中读取数据到对象，并显示出来
        ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream("day5\\src\\cn\\gok\\homework\\1.dat"));
        School s1 = new School("泉职大", "晋江", 2002);
        School s2 = new School("泉大", "晋江", 2010);
        stream.writeObject(s1);
        stream.writeObject(s2);
        stream.close();
        System.out.println("写入成功");
    }
}
